package com.appspot.zcmjqm.web;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.appspot.zcmjqm.app.model.Cart;
import com.appspot.zcmjqm.app.model.Product;
import com.appspot.zcmjqm.service.ProductService;

@Controller
@SessionAttributes({"cart"})
@RequestMapping("/cart")
public class CartControllerWebMVCImpl implements CartController {
	
	@Autowired
	private ProductService productService;

	@RequestMapping("/show.do")
	public ModelAndView displayCart(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(null == cart) {
			cart = new Cart();
			cart.setProducts(new ArrayList<Product>());
		}
		mav.addObject("cart", cart);
		mav.setViewName("cart");
		return mav;
	}

	@RequestMapping("/add.do")
	public ModelAndView newProduct(HttpServletRequest request, @RequestParam String productKey) {
		ModelAndView mav = new ModelAndView();
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(null == cart) {
			cart = new Cart();
			cart.setProducts(new ArrayList<Product>());
		}
		
		Product p = productService.getById(productKey);
		cart.getProducts().add(p);
		
		mav.addObject("cart", cart);
		mav.setViewName("redirect:/home/show.do");
		return mav;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

}